package com.lagou.rabbitmq.service;

import com.lagou.rabbitmq.dao.GoodDao;
import com.lagou.rabbitmq.dao.OrdersDao;
import com.lagou.rabbitmq.pojo.Orders;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.stereotype.Service;
import org.springframework.amqp.core.*;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Service
public class OrdersService {

    private Integer second = 120;

    @Resource
    private GoodDao goodDao;
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void placeOrder(int userId, int goodId) throws UnsupportedEncodingException {
        int result = goodDao.inventorySubById(goodId);
        if (result != 1) {
            throw new RuntimeException("下单失败");
        }
        Orders orders = new Orders();
        orders.setGoodId(goodId);
        orders.setUserId(userId);
        orders.setState(0);
        ordersDao.save(orders);

        final MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                // 设置消息的过期时间
                .setHeader("x-delay", (second - 10) * 1000)
                .setContentEncoding("utf-8")
                .build();

        final Message message = MessageBuilder
                .withBody(String.valueOf(orders.getId()).getBytes(StandardCharsets.UTF_8))
                .andProperties(messageProperties)
                .build();

        amqpTemplate.send("ex.delayed", "key.delayed", message);
    }

    @Transactional
    public void pay(int ordersId) {
        Orders orders = new Orders();
        orders.setId(ordersId);
        orders.setState(1);
        ordersDao.save(orders);
    }

}
